<script setup lang="ts">
import type { AppTypeProps } from '@/types';

import {
  type ComponentInternalInstance,
  defineAsyncComponent,
  getCurrentInstance,
  hydrateOnVisible,
  ref,
  useTemplateRef,
} from 'vue';

import { ElCollapse, ElCollapseItem, ElMessage } from 'element-plus';
import { customAlphabet } from 'nanoid';

import { dynamicApps, loadApps, sysAppList } from '@/model/app';

import AppIcon from './components/manager/AppIcon.vue';

defineOptions({ name: 'SystemAppManager' });
const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyz', 10);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const baseUrl = proxy?.$config.baseUrl;
const AppEdit = defineAsyncComponent({
  hydrate: hydrateOnVisible(),
  loader: () => import('../_core/common/AppEdit.vue'),
});
const activeNames = ref(['app-list', 'dynamic-list']);
const appEditElRef = useTemplateRef('appEditElRef');

// const _sysAppList = ref(sysAppList);
// const _dynamicApps = ref(dynamicApps);
const refreshAppList = (data: AppTypeProps) => {
  if (
    ![...sysAppList.value, ...dynamicApps.value].some(
      (item) => item.key === data.key,
    )
  ) {
    dynamicApps.value.push(data);
    return;
  }
  sysAppList.value.map((item) => {
    if (item.key === data.key) {
      Object.assign(item, data);
    }
    return item;
  });
  dynamicApps.value.map((item) => {
    if (item.key === data.key) {
      Object.assign(item, data);
    }
    return item;
  });
};
const onEdit = (item: AppTypeProps) => {
  appEditElRef.value?.show(item);
};
const onDelete = (data: AppTypeProps) => {
  if (!data || !data.key) return;
  // 删除对应的图标
  const url = `${baseUrl}/app/delete/${data.key}?type=${data.type || 'custom'}`;
  fetch(url, { method: 'DELETE' })
    .then((response) => response.json())
    .then(async (res) => {
      const { code, msg } = res;
      if (code === 200) {
        await loadApps();
        // sysAppList = sysAppList.filter((item) => {
        //   return item.key !== data.key;
        // });
        // dynamicApps = dynamicApps.filter((item) => {
        //   return item.key !== data.key;
        // });
      } else {
        ElMessage.error(msg || '删除失败，请稍后再试');
      }
    });
};
// 修改应用
function onBuildApp(data: AppTypeProps) {
  const id = data.key;
  const url = `${baseUrl}/app/save/${id}`;
  fetch(url, {
    body: JSON.stringify(data),
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
    },
    method: 'POST',
  })
    .then((response) => response.json())
    .then(async (res) => {
      const { code, msg } = res;
      if (code === 200) {
        await loadApps();
        refreshAppList(data);
        ElMessage.success(msg || '应用信息保存成功');
      } else {
        ElMessage.error(msg || '删除失败，请稍后再试');
      }
    });
}
const onNewApp = () => {
  appEditElRef.value?.open({
    label: '新建应用',
    value: `${nanoid(10)}`,
  });
};
</script>
<template>
  <div class="wos-app-manager">
    <ElCollapse v-model="activeNames">
      <ElCollapseItem name="app-list" title="系统图标">
        <div class="app-list">
          <template v-for="item in sysAppList" :key="item.key">
            <AppIcon :item="item" @delete="onDelete" @edit="onEdit" />
          </template>
        </div>
      </ElCollapseItem>
      <ElCollapseItem name="dynamic-list" title="应用图标">
        <div class="app-list">
          <template v-for="item in dynamicApps" :key="item.key">
            <AppIcon :item="item" @delete="onDelete" @edit="onEdit" />
          </template>
          <div class="app-item">
            <div class="app-item-new" title="新建图标" @click="onNewApp">+</div>
          </div>
        </div>
      </ElCollapseItem>
    </ElCollapse>
    <Teleport to="body">
      <AppEdit ref="appEditElRef" @confirm="onBuildApp" />
    </Teleport>
  </div>
</template>
<style lang="scss">
@import url('./css/manager.scss');
</style>
